package org.train.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
public class WebSecurityBeans{
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    // 身份认证处理逻辑
    @Bean
    public AuthenticationProvider authenticationProvider(){
        return new AuthenticationProvider(){
            @Override
            public Authentication authenticate(Authentication authentication) throws AuthenticationException{
                String username = authentication.getName();
                String password = authentication.getCredentials().toString();
                UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                if(!passwordEncoder.matches(password, userDetails.getPassword())){
                    throw new BadCredentialsException("密码错误");
                }
                return new UsernamePasswordAuthenticationToken(userDetails, null, null);
            }

            @Override
            public boolean supports(Class<?> authentication){
                return true;
            }
        };
    }
}
